import {momentumInfo, Options} from "../types";

export function momentum(
  current: number,
  start: number,
  time: number,
  lowerMargin: number,
  upperMargin: number,
  wrapperSize: number,
  options: Options
): momentumInfo {
  // debugger;
  const distance = current - start;
  const speed = Math.abs(distance) / time;

  let { deceleration, swipeBounceTime, swipeTime } = options
  let duration = swipeTime // momentum动画持续时间
  const rate = 15;

  // deceleration是momentum动画的减速度
  let destination = current + speed / deceleration * (distance < 0 ? -1 : 1);
  let needReset = false;

  if (destination < lowerMargin) { // 超出了底部范围
    // 本来只要控制在范围内就行了，但可能要触发加载更多，所以要适当超出范围
    destination = wrapperSize ? Math.max(lowerMargin - wrapperSize / 4, lowerMargin - (wrapperSize / rate * speed)) : lowerMargin;
    duration = swipeBounceTime;
    needReset = true;
  } else if (destination > upperMargin) {
    destination = wrapperSize ? Math.min(upperMargin + wrapperSize / 4, upperMargin + wrapperSize / rate * speed) : upperMargin;
    duration = swipeBounceTime;
    needReset = true;
  }
  return {
    destination: Math.round(destination),
    duration,
    needReset
  }
}
